package com.umfwechat.lightprogram.interceptor;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.umfwechat.common.constant.CacheConsts;
import com.umfwechat.util.RedisUtil;

import net.sf.json.JSONObject;

public class AuthoInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(AuthoInterceptor.class);
	JSONObject jsonObject = new JSONObject();

	public boolean process(String data){ 
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest request = sra.getRequest();
		String url = request.getRequestURL().toString();
		String uri = request.getRequestURI();
		logger.info("请求的路径为："+url);
		JSONObject param=JSONObject.fromObject(data);
		logger.info("请求的入参："+param.toString());
		System.err.println("请求的入参："+param.toString());
		String tokenId = param.optString("loginToken");	//用户凭证
		logger.info("入参用户凭证tokenId："+tokenId);
		if(tokenId !=null && !"".equals(tokenId)){
			String userId = param.optString("loginUserId");	//用户凭证
			String agentId = param.optString("loginAgentId");	//用户凭证
			String loginMessage;
			try {
				loginMessage = RedisUtil.get(CacheConsts.LOGIN+agentId+userId);
				logger.info("缓存中的用户信息："+loginMessage);
			} catch (Exception e) {
				logger.info("获取缓存信息异常"+e);
				jsonObject.put("retCode","0001");
				jsonObject.put("retMsg","获取缓存信息异常");
				return true;
			}
			if(loginMessage ==null ){
				logger.info("4001，登陆session超过有效期");
				jsonObject.put("retCode", "4001");
				jsonObject.put("retMsg", "登陆超时");
				return true;
			}
			String[] split = loginMessage.split(",");
			if(split.length<4){
				logger.info("登陆时参数缓存参数不足，为了兼容已有功能");
				jsonObject.put("retCode", "4001");
				jsonObject.put("retMsg", "请重新登陆"); 
				return true;
			}
			String tokenIdRedis = split[3];
			logger.info("缓存中的用户凭证tokenIdRedis："+tokenIdRedis);
			System.out.println("缓存中的用户凭证tokenIdRedis=="+tokenIdRedis);
			if(!tokenId.equals(tokenIdRedis)){
				logger.info("4002，该账户被异地登陆，异地登陆信息为："+loginMessage);
				jsonObject.put("retCode","4002");
				jsonObject.put("retMsg", "该账户被异地登陆");
				return true;
			}
			logger.info("验证通过");
			return false;
		}else{
			if(!url.contains("loginOn") && !url.contains("posCallbackMethod")){
				logger.info("tokenId为空，未登陆，请登陆，请求路径为："+url);
				jsonObject.put("retCode", "0001");
				jsonObject.put("retMsg", "未登陆，请登陆");
				return true;
			}
		}
		return false;
	}

	public JSONObject result() {
		return jsonObject;
	}
}
